<template>
  <view>
    <u-popup mode="right" round="5rpx" :show="show" @close="close">
      <view class="popup-content">
        <view class="u-wrap">
          <view class="u-search-box flex items-center">
            <view class="flex-auto">
              <text class="title p-10rpx block font-bold">选择原料</text>
            </view>
            <view class="u-search-inner">
              <u-search
                shape="square"
                placeholder="请输入原料名称"
                v-model="filterPam.name"
                search-icon-size="15rpx"
                @custom="onSearch"
                @clear="onSearch"
              ></u-search>
            </view>
          </view>
          <view class="u-menu-wrap">
            <scroll-view
              scroll-y
              scroll-with-animation
              class="u-tab-view menu-scroll-view"
              :scroll-top="config.scrollTop"
            >
              <view
                v-for="(item, index) in typelist"
                :key="index"
                class="u-tab-item"
                :class="[config.current == index ? 'u-tab-item-active' : '']"
                :data-current="index"
                @tap.stop="swichMenu(index, item)"
              >
                <text class="u-line-1">{{ item.name }}</text>
              </view>
            </scroll-view>
            <block v-for="(item, index) in typelist" :key="index">
              <scroll-view scroll-y class="right-box" v-if="config.current == index">
                <view class="page-view">
                  <view class="class-item">
                    <view class="item-title">
                      <text>{{ item.name }}</text>
                    </view>
                    <u-checkbox-group>
                      <view class="item-container">
                        <view
                          @click="changeSelect(item1)"
                          class="thumb-box"
                          v-for="(item1, index1) in dataList"
                          :key="index1"
                        >
                          <view class="item-menu-image-box">
                            <view class="select-box">
                              <u-checkbox
                                active-color="var(--kui-color-theme)"
                                :checked="isChecked(item1)"
                              ></u-checkbox>
                            </view>
                            <image class="item-menu-image" src="/static/images/icons/icon-source.svg" mode=""></image>
                          </view>
                          <view class="item-menu-name">{{ item1.name }}</view>
                        </view>

                        <view v-if="dataList.length === 0" class="w-full mt-20rpx">
                          <u-empty mode="data" text="暂无原料数据"></u-empty>
                        </view>

                        <view class="w-full mt-10rpx" @click="loadmore">
                          <u-line margin="0.5em 0" />
                          <u-text :text="filterPam.total > dataList.length ? '点击查看更多' : '到底了~'" type="info" align="center"></u-text>
                        </view>
                      </view>
                    </u-checkbox-group>
                  </view>
                </view>
              </scroll-view>
            </block>
          </view>
        </view>

        <!-- 选中操作弹窗 -->
        <view class="popup-footer" v-if="selectItem.length > 0">
          <view class="text-base justify-end">已选择 {{ selectItem.length }} 个原料</view>
          <view class="popup-btn flex justify-end">
            <view class="mr-5rpx"><u-button @click="selectItem.length = 0" type="error">清除</u-button></view>
            <view class="mr-5rpx"><u-button @click="confirmData" type="primary">确定</u-button></view>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>
<script setup>
import { reactive, ref, onMounted, computed } from "vue";
import { materialRecipeLevelList, materialRecipeLevelTypeList } from "@/api";

const config = reactive({
  scrollTop: 0, //tab标题的滚动条位置
  current: 0, // 预设当前项的值
  menuHeight: 0, // 左边菜单的高度
  menuItemHeight: 0, // 左边菜单item的高度
});

const show = ref(false);
const open = (data) => {
  if (data) {
    config.value = { ...data };
  }
  getTypeData();
  getData(true);
  show.value = true;
};
const close = () => {
  // 清除选择
  selectItem.value = [];
  filterPam.name = "";
  // 关闭
  show.value = false;
};

const loadmore = () => {
  filterPam.current += 1;
  getData();
};

defineExpose({ open, close });

const emits = defineEmits(["confirm", "cancel"]);

const swichMenu = async (index, item) => {
  // console.log("swichMenu ", index, config.current);
  if (index == config.current) return;
  config.current = index;
  // 如果为0，意味着尚未初始化
  // if (config.menuHeight == 0 || config.menuItemHeight == 0) {
  //   await getElRect("menu-scroll-view", "menuHeight");
  //   await getElRect("u-tab-item", "menuItemHeight");
  // }
  // 将菜单菜单活动item垂直居中
  config.scrollTop = index * config.menuItemHeight + config.menuItemHeight / 2 - config.menuHeight / 2;

  // 更新数据
  getData(true, item.materialRecipeLevelId);
};

const getElRect = async (elClass, dataVal) => {
  return new Promise((resolve, reject) => {
    const query = uni.createSelectorQuery().in(this);
    query
      .select("." + elClass)
      .fields({ size: true }, (res) => {
        // 如果节点尚未生成，res值为null，循环调用执行
        if (!res) {
          setTimeout(() => {
            this.getElRect(elClass);
          }, 10);
          return;
        }
        this[dataVal] = res.height;
      })
      .exec();
  });
};

const filterPam = reactive({
  name: "", // 搜索框的值
  current: 1,
  size: 20,
  total: 0,
});

// 加载数据
const dataList = ref([]);
const getData = async (isReload = false, parentId) => {
  uni.showLoading({ title: "加载中", mask: true });
  const currTab = typelist.value[config.current];
  try {
    const pam = {
      dataType: 2,
      parentId: parentId || currTab?.materialRecipeLevelId || "",
      ...filterPam,
    };
    // console.log("pam ", pam, config.current, typelist);
    if (isReload) {
      pam.current = 1;
      dataList.value = [];
    }
    const { data, success } = await materialRecipeLevelList(pam);
    if (!success) throw Error("获取数据失败");
    dataList.value = [...dataList.value, ...data.records];
    filterPam.total = data.total;

    uni.hideLoading();
  } catch (error) {
    console.error("获取数据失败", error);
    uni.hideLoading();
  }
};

const onSearch = () => {
  getData(true);
};

const typelist = ref([]);
const getTypeData = async () => {
  uni.showLoading({ title: "加载中", mask: true });
  try {
    const pam = {
      // parentId: 0,
      dataType: 1,
      baseLevel: 1,
    };
    const { data, success } = await materialRecipeLevelTypeList(pam);
    if (!success) throw Error("获取数据失败");
    typelist.value = [{ name: "全部", materialRecipeLevelId: "" }, ...data];
    uni.hideLoading();
  } catch (error) {
    console.error("获取数据失败", error);
    uni.hideLoading();
  }
};

// 选中的项
const selectItem = ref([]);

const changeSelect = (item) => {
  item.selected = !item.selected;
  const findIndex = selectItem.value.findIndex((i) => i.materialRecipeLevelId == item.materialRecipeLevelId);
  if (item.selected == true) {
    if (findIndex == -1) {
      selectItem.value.push(item);
    } else {
      console.log("已存在");
      // uni.showToast({ title: "已存在", icon: "none" });
    }
  } else {
    selectItem.value.splice(findIndex, 1);
  }
};

// 查询是否选中
const isChecked = computed(() => {
  return (item) => {
    return selectItem.value.findIndex((i) => i.materialRecipeLevelId == item.materialRecipeLevelId) != -1;
  };
});

const confirmData = () => {
  emits("confirm", selectItem.value);
  close();
};

// onMounted(() => {

// });
</script>

<style scoped lang="scss">
.popup-content {
  max-width: 400rpx;
  width: 400rpx;
  position: relative;

  .title {
    font-weight: bold;
  }

  .textarea {
    width: 80%;
    margin: 10rpx 0rpx;

    ::v-deep .u-textarea__field {
      font-size: 13rpx;
    }
  }

  .btns {
    display: flex;
    width: fit-content;
    justify-content: space-between;
    margin-top: 20rpx;

    .btns-item {
      margin: 0rpx 15rpx;

      ::v-deep .u-button {
        padding: 2rpx 20rpx;
      }
    }
  }

  .popup-footer {
    position: absolute;
    bottom: 20rpx;
    width: 60%;
    background-color: white;
    padding: 10rpx;
    box-shadow: 1rpx 1rpx 5rpx #ccc;
    border-radius: 5rpx;
    right: 20rpx;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
}

.u-wrap {
  height: calc(100vh);
  /* #ifdef H5 */
  height: calc(100vh - var(--window-top));
  /* #endif */
  display: flex;
  flex-direction: column;
}

.u-search-box {
  padding: 5rpx 8rpx;
}

.u-menu-wrap {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.u-search-inner {
  display: flex;
  align-items: center;
}

.u-search-text {
  font-size: 12rpx;
  color: $u-tips-color;
  margin-left: 10rpx;
}

.u-tab-view {
  width: 150rpx;
  height: 100%;
}

.u-tab-item {
  height: 30rpx;
  background: #f6f6f6;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10rpx;
  color: #444;
  font-weight: 400;
  line-height: 1;
}

.u-tab-item-active {
  position: relative;
  color: #000;
  font-size: 10rpx;
  font-weight: 600;
  background: #fff;
}

.u-tab-item-active::before {
  content: "";
  position: absolute;
  border-left: 4px solid var(--kui-color-theme);
  height: 30rpx;
  left: 0;
  top: 0rpx;
}

.u-tab-view {
  height: 100%;
}

.right-box {
  background-color: rgb(250, 250, 250);
}

.page-view {
  padding: 16rpx;
}

.class-item {
  margin-bottom: 30rpx;
  background-color: #fff;
  padding: 16rpx;
  border-radius: 8rpx;
}

.item-title {
  font-size: 10rpx;
  font-weight: bold;
}

.item-menu-name {
  font-weight: normal;
  font-size: 11rpx;
}

.item-container {
  display: flex;
  flex-wrap: wrap;
}

.thumb-box {
  width: 33.333333%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  margin-top: 20rpx;
}

.item-menu-image-box {
  position: relative;

  .select-box {
    position: absolute;
    right: 0;
    top: 0;
    z-index: 2;
    box-sizing: border-box;
  }
}

.item-menu-image {
  box-sizing: border-box;
  width: 50rpx;
  height: 50rpx;
  background-color: rgb(235, 235, 235);
  border-radius: 5rpx;
  margin-bottom: 5rpx;
  padding: 10rpx;
}

::v-deep .u-checkbox-group--row {
  display: block;
}
</style>
